<?php

namespace App\Services\Message;

use App\Models\Wxuser;
use Auth;

/**
 * 消息推送服务
 * @package App\Services
 */
class MessageService
{
    //向微信服务器发送subscribeMessage订阅消息
    /**
     * @param Wxuser $wxuser 发送给谁
     * @param $notifyType notify给村干部，remind给村民  取不同类型的通知模板
     * @param $data 发送的数据
     * @return mixed
     */
    public function send(Wxuser $wxuser, $notifyType, $data)
    {
        $res = $this->getAccess();
        $access_token = $res->access_token;
        return $this->sendMessage($access_token, $wxuser, $notifyType, $data);
    }

    protected function getAccess()
    {
        //小程序appid appsecret
        $appid = env('APP_ID');
        $appsecret = env("APP_SECRET");
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
        $client = new \GuzzleHttp\Client();
        $response = $client->get($url);
        $result = $response->getBody()->getContents();
        return json_decode($result);
    }

    protected function sendMessage($access_token, Wxuser $wxuser, $notifyType, $data)
    {


        //获取接口凭证
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$access_token;
        $headers = [
            'Content-Type' => 'application/json',
        ];
        $client = new \GuzzleHttp\Client();
        //notifyType 判断类型为notice（回复） 还是 remind（提醒发起人）
        //notice时 使用TEMPLATE_NOTICE_ID remind时使用TEMPLATE_REMIND_ID

        $response = $client->post($url, [
            'headers' => $headers,
            'body' => json_encode([
                    'access_token' => $access_token,
                    'touser' => $wxuser->openid,
                    'template_id' => $notifyType == 'notice' ? env("TEMPLATE_NOTICE_ID") : env("TEMPLATE_REMIND_ID"),
                    'page' => "pages/home/index",
                    'data' => $data,
                    'miniprogram_state' => "developer" //配置环境、线上环境、开发环境
                ]
            )
        ]);
        $result = $response->getBody()->getContents();
        $result = json_decode($result, true);
        return $result;
    }
}
